package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.lang.annotation.Retention;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;


    /**
     * 根据套餐分类id，查询套餐列表
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmeal",key = "#categoryId + ':' +#status")
    public R listByCategoryId(Long categoryId,Integer status){
        // select * from setmeal where category_id = ? and status = ?
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getCategoryId,categoryId);
        qw.eq(Setmeal::getStatus,status);
        List<Setmeal> list = setmealService.list(qw);
        return R.success(list);
    }


    //清除
    @CacheEvict(value = "setmeal",allEntries = true)
    @PutMapping
    public R<String> updateSetmeal(@RequestBody SetmealDto setmealDto){
        // 新建一个业务层方法
        setmealService.updateSetmeal(setmealDto);
        return R.success("修改套餐成功");
    }


    @GetMapping("/{id}")
    public R queryById(@PathVariable Long id){
        //1、根据套餐id查询套餐数据 select * from setmeal where id =?
        Setmeal setmeal = setmealService.getById(id);

        //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishList = setmealDishService.list(qw);

        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        SetmealDto setmealDto = new SetmealDto();
        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmeal,setmealDto);
        // 3.2、将setmealDishList 设置到 setmealDto中
        setmealDto.setSetmealDishes(setmealDishList);
        //4、返回 setmealDto
        return R.success(setmealDto);
    }

    //清除
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,
                          @RequestParam List<Long> ids){
        // 批量更新套餐的状态status：
        // update setmeal set status = ? where id in (1,2,3)
        LambdaUpdateWrapper<Setmeal> qw = new LambdaUpdateWrapper<>();
        qw.set(Setmeal::getStatus,status);//set status = ?
        qw.in(Setmeal::getId,ids);//where id in (1,2,3)
        setmealService.update(qw);
        return R.success("更新成功！！");
    }

    //清除
    @CacheEvict(value = "setmeal",allEntries = true)
    @DeleteMapping
    public R<String> deleteByIds( @RequestParam List<Long> ids  ){
        //新定义一个业务层的方法来完成套餐删除
        setmealService.deleteSetmeal(ids);
        return R.success("删除成功");
    }


    @GetMapping("/page")
    public R<Map<String,Object>> pageQuery(Integer page,Integer pageSize,String name){
        //1、封装分页参数
        IPage<Setmeal> pageInfo = new Page<>(page,pageSize);
        //2、封装查询条件 where name like '%xxx%'
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        setmealService.page(pageInfo,qw);

        //3、获取查询结果：直接使用pageInfo，或者重新封装map数据，此处选择使用后者
        long total = pageInfo.getTotal();
        Map<String,Object> map = new HashMap<>();
        map.put("total",(int)total);


        List<Setmeal> records = pageInfo.getRecords();
        // 问题： List<Setmeal> records 数据的Setmeal中压根就没有categoryName属性
        // 解决： SetmealDto实体类中有categoryName属性
        // 将List<Setmeal> ---> 重新封装成 List<SetmealDto>
        List<SetmealDto> setmealDtoList = new ArrayList<>();

        for (Setmeal setmeal : records) {
            // Setmeal setmeal --> SetmealDto setmealDto
            SetmealDto setmealDto = new SetmealDto();
            // 将setmeal对象的属性值 拷贝到 setmealDto对象中 BeanUtils.copyProperites(,)
            BeanUtils.copyProperties(setmeal,setmealDto);
            // 获取categoryName值 ，然后set到setmealDto对象中：
            Long categoryId = setmeal.getCategoryId();
            // 根据分类id查询分类信息：SELECT * FROM category WHERE id = 1413342269393674242
            Category category = categoryService.getById(categoryId);
            setmealDto.setCategoryName(category.getName());
            //将setmealDto对象放入 setmealDtoList 集合中
            setmealDtoList.add(setmealDto);
        }
        map.put("records",setmealDtoList);
        return R.success(map);
    }


    //清除
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping
    public R<String> addSetmeal(@RequestBody SetmealDto setmealDto){
        setmealService.addSetmeal(setmealDto);
        return R.success("保存套餐成功!!");
    }
}
